<?php
/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * For more information, see <http://www.aljey.com>.
 */

namespace Al\HTTP\Lib\Vars;

use Al\Core\Lib\ParameterHolder,
    Al\Core\Lib\Service,
    Al\HTTP\Exception\UploadException;

/**
 * Provides an array-like wrapper for $_FILES with a standardized structure for
 * multiple and single uploads.
 * Reads mime-type and guesses an extension based on that, and since they are
 * not provided by the client those extensions can be trusted even by
 * server-side validation.
 * 
 * @author Eugene Kuzmenko <mail@aljey.com>
 */
class Files extends ParameterHolder {

  /** {@inheritDoc} */
  public function __construct() {
    $data = array();
    $finfo = new \finfo(FILEINFO_MIME);
    foreach ($_FILES as $key => $file) {
      $tmps = is_array($file['tmp_name']) ? $file['tmp_name'] :
        array($file['tmp_name']);
      $names = is_array($file['name']) ? $file['name'] : array($file['name']);
      $sizes = is_array($file['size']) ? $file['size'] : array($file['size']);
      $errors = is_array($file['error']) ? $file['error'] :
        array($file['error']);
      foreach ($tmps as $num => $tmp) {
        if ($errors[$num] === UPLOAD_ERR_NO_FILE) continue;
        if ($errors[$num] !== UPLOAD_ERR_OK) {
          throw new UploadException($errors[$num]);
        }
        $mime = explode(';', $finfo->file($tmp));
        if (!($ext = Service::get("mime.ext.$mime[0]"))) {
          throw new \RuntimeException("Unknown mime type $mime[0]");
        }
        if (!isset($data[$key])) $data[$key] = array();
        $data[$key][] = array(
          'name' => $names[$num],
          'ext' => $ext,
          'uid' => uniqid() . ".$ext",
          'tmp' => $tmp,
          'size' => $sizes[$num],
        );
      }
    }
    parent::__construct($data);
  }

  /**
   * Moves uploaded files to a specified directory.
   *
   * @param array $files Files to move.
   * @param string $path A directory to put the files into.
   */
  private function doMove($files, $path) {
    foreach ($files as $file) {
      move_uploaded_file($file['tmp'], "$path/{$file['uid']}");
    }
  }

  /**
   * Moves files by name.
   *
   * @param string $path
   * @param string $name [optional]
   */
  public function move($path, $name = null) {
    @mkdir($path, 0777, true);
    if (is_null($name)) {
      foreach ($this as $files) $this->doMove($files, $path);
    } elseif ($this[$name]) {
      $this->doMove($this[$name], $path);
    }
  }
  
}